/** 
  基地考核设置
*/
<template>
  <div>
    <condition-card ref="baseAssessSetCondition" @reset="reset" @search="onSubmit" label-position="right" label-width="150px">
      <el-row :gutter="24" style="height: 50px;">
        <el-col :span="8">
          <el-form-item :label="$t('baseAssessSetting.examinationBatch')">
            <el-date-picker
              style="width: 100%"
              v-model="queryForm.condition.batch"
              value-format="yyyy-MM"
              type="month"
              :placeholder="$t('graduateBase.chooseMonth')">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('baseAssessSetting.baseLevel')">
            <el-select v-model="queryForm.condition.baseLevel" @change="changeBaseLevel" clearable style="width: 100%">
              <el-option
                v-for="item in options.baseLevel"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('templateSetting.assessmentTemplate')">
            <el-select v-model="queryForm.condition.templateId" clearable style="width: 100%">
              <el-option
                v-for="item in options.templateId"
                :key="item.templateId"
                :label="item.templateName"
                :value="item.templateId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24" style="height: 50px;">
        <el-col :span="8">
          <el-form-item :label="$t('baseAssessSetting.currentStauts')">
            <el-select v-model="queryForm.condition.publishStatus" clearable style="width: 100%">
              <el-option
                v-for="item in options.publishStatus"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('baseAssessSetting.submitMaterialsStart')">
            <el-date-picker
              style="width: 100%"
              v-model="queryForm.condition.submitMaterialsStart"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              :placeholder="$t('graduateBase.chooseDateAndTime')"
              :picker-options="clbssjqPickerOptions">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('baseAssessSetting.submitMaterialsEnd')">
            <el-date-picker
              style="width: 100%"
              v-model="queryForm.condition.submitMaterialsEnd"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              :placeholder="$t('graduateBase.chooseDateAndTime')"
              :picker-options="clbssjzPickerOptions">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24" style="height: 50px;">
        <el-col :span="8">
          <el-form-item :label="$t('baseAssessSetting.onSiteAssessTimeStart')">
            <el-date-picker
              style="width: 100%"
              v-model="queryForm.condition.onSiteExamineStart"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              :placeholder="$t('graduateBase.chooseDateAndTime')"
              :picker-options="xckhsjqPickerOptions">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('baseAssessSetting.onSiteAssessTimeEnd')">
            <el-date-picker
              style="width: 100%"
              v-model="queryForm.condition.onSiteExamineEnd"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              :placeholder="$t('graduateBase.chooseDateAndTime')"
              :picker-options="xckhsjzPickerOptions">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="height: 50px;">
        <el-col :span="8" :gutter="24" style="padding-right: 16px;">
          <el-form-item :label="$t('baseAssessSetting.ratingTimeStart')">
            <el-date-picker
              style="width: 100%"
              v-model="queryForm.condition.scoreStart"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              :placeholder="$t('graduateBase.chooseDateAndTime')"
              :picker-options="pfsjqPickerOptions">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8" style="padding-left: 8px;padding-right: 8px;">
          <el-form-item :label="$t('baseAssessSetting.ratingTimeEnd')">
            <el-date-picker
              style="width: 100%"
              v-model="queryForm.condition.scoreEnd"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              :placeholder="$t('graduateBase.chooseDateAndTime')"
              :picker-options="pfsjzPickerOptions">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    </condition-card>
    <el-card shadow="never" v-loading="loading" body-style="padding: 24px;" class="card-margin">
      <h1 class="condition-title">{{ $t('baseAssessSetting.baseExamSetList') }}</h1>
      <div class="edu-opertion-bar sub-title">
        <div class="float-right" style="display: flex;">
          <el-button v-if="permitToExport" @click="exportBaseAssessSet">{{$t('common.btn.export')}}</el-button>
          <el-button v-if="permitToAdd" type="primary" @click="addBaseAssessSet">{{$t('common.btn.add')}}</el-button>
        </div>
      </div>
      <edu-table :pagination="false" :order='false' :tooltipEffect="tooltipEffect" stripe :data="dataList" size="mini" @selection-change="handleSelectionChange">
        <edu-table-column :label="$t('baseAssessSetting.examinationBatch')" prop="batch"></edu-table-column>
        <edu-table-column :label="$t('baseAssessSetting.baseLevel')" prop="baseLevelName"></edu-table-column>
        <edu-table-column :label="$t('templateSetting.assessmentTemplate')" prop="templateName"></edu-table-column>
        <edu-table-column :label="$t('baseAssessSetting.materialSubmissionTime')" prop="submitMaterialsTime">
          <template slot-scope="scope">
            {{ scope.row.submitMaterialsStart }} {{ $t('graduateBase.to') }} {{ scope.row.submitMaterialsEnd }}
          </template>
        </edu-table-column>
        <edu-table-column :label="$t('baseAssessSetting.onSiteAssessTime')" prop="onSiteExamineTime">
          <template slot-scope="scope">
            {{ scope.row.onSiteExamineStart }} {{ $t('graduateBase.to') }} {{ scope.row.onSiteExamineEnd }}
          </template>
        </edu-table-column>
        <edu-table-column :label="$t('baseAssessSetting.ratingTime')" prop="scoreTime">
          <template slot-scope="scope">
            {{ scope.row.scoreStart }} {{ $t('graduateBase.to') }} {{ scope.row.scoreEnd }}
          </template>
        </edu-table-column>
        <edu-table-column :label="$t('baseAssessSetting.currentStauts')" prop="publishStatusName">
          <template slot-scope="scope">
            <div class="publish-btn-container">
              <el-button v-if="scope.row.publishStatus === 0" type="danger" plain>{{ scope.row.publishStatusName }}</el-button>
              <el-button v-else type="success" plain>{{ scope.row.publishStatusName }}</el-button>
            </div>
          </template>
        </edu-table-column>
        <edu-table-column :label="$t('common.text.operation')" fit width="200">
          <template slot-scope="scope">
            <el-button v-if="permitToPublish" type="text" @click="publishBaseAssessSet(scope.row)">{{$t('common.btn.publish')}}</el-button>
            <el-button v-if="permitToEdit" type="text" @click="editBaseAssessSet(scope.row)">{{$t('common.btn.edit')}}</el-button>
            <el-button v-if="permitToDelete" type="text" @click="deleteBaseAssessSet(scope.row)">{{$t('common.btn.delete')}}</el-button>
            <el-button v-if="permitToDetail" type="text" @click="selectBaseAssessSetDetail(scope.row)">{{$t('graduateBase.details')}}</el-button>
          </template>
        </edu-table-column>
      </edu-table>
      <el-row type="flex" class="row-bg" justify="end">
        <el-col>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryForm.pageNum_"
            :page-sizes="[20, 40, 80, 100]"
            :page-size="queryForm.pageSize_"
            layout="total, sizes, prev, pager, next, jumper"
            :total="queryForm.total_"
            style="float:right;margin-top:10px"
          ></el-pagination>
        </el-col>
      </el-row>
    </el-card>
    <el-dialog
      :before-close="beforeClose"
      width="50%"
      class="base-assess-set-dialog"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false">
        <maintain-base-assess-set ref="mainBaseAssessSet"
        :dialogVisible="dialogVisible"
        :mainBaseAssessInfo="mainBaseAssessInfo"
        :dialogMode="dialogMode" 
        @close-base-assess-set="beforeClose"
        @refresh-base-assess-set="onSubmit">
      </maintain-base-assess-set>
    </el-dialog>
    <edu-export-dialog
      :disabled="exportButton"
      :title="$t('message.prompt')"
      ref="downloadRef"
      :data="exportResult">
    </edu-export-dialog>
  </div>
</template>
<script>
import graduateStudentApi from 'common/src/api/graduateStudent/graduateStudent';
import mainTainBaseAssessSet from './mainTainBaseAssessSet.vue';
export default {
  components: {
    'maintain-base-assess-set': mainTainBaseAssessSet
  },
  data () {
    return {
      auths: [],
      permitToExport: false,
      permitToAdd: false,
      permitToPublish: false,
      permitToEdit: false,
      permitToDelete: false,
      permitToDetail: false,
      queryForm: {
        pageNum_: 1,
        pageSize_: 20,
        total_: 0,
        condition: {
          batch: '', // 考核批次
          baseLevel: '', // 基地级别
          templateId: '', // 考核模板
          publishStatus: '', // 基地考核设置发布状态（当前状态）
          submitMaterialsStart: '', // 材料报送时间起（有效日期起）
          submitMaterialsEnd: '', // 材料报送时间止（有效日期止）
          onSiteExamineStart: '', // 现场考核时间起
          onSiteExamineEnd: '', // 现场考核时间止
          scoreStart: '', // 评分时间起
          scoreEnd: '' // 评分时间止
        }
      },
      dataList: [],
      exportButton: false,
      exportResult: null,
      indexKey: '1', // 面包屑
      title: '',
      multipleSelection: [],
      options: {
        // 基地级别
        baseLevel: [
          {
            label: '校级',
            value: '1'
          },
          {
            label: '院级',
            value: '2'
          }
        ],
        // 考核模板
        templateId: [],
        publishStatus: [
          {
            label: '未发布',
            value: 0
          },
          {
            label: '已发布',
            value: 1
          }
        ]
      },
      dialogMode: 'add',
      mainBaseAssessInfo: {},
      dialogVisible: false,
      dialogMultipleSelection: []
    }
  },
  computed: {
    clbssjqPickerOptions() {
      let _this = this;
      return {
        disabledDate: (value) => {
          if (_this.queryForm.condition.submitMaterialsEnd) {
            // 材料报送开始时间必须小于材料报送截止时间
            if (value.getTime() > new Date(_this.queryForm.condition.submitMaterialsEnd.split(' ')[0]).getTime()) {
              return true;
            }
          }
          return false;
        }
      };
    },
    clbssjzPickerOptions() {
      let _this = this;
      return {
        disabledDate: (value) => {
          if (_this.queryForm.condition.submitMaterialsStart) {
            // 材料报送截止时间必须大于材料报送开始时间
            if (value.getTime() + (24 * 60 * 60 * 1000) < new Date(_this.queryForm.condition.submitMaterialsStart.split(' ')[0]).getTime()) {
              return true;
            }
          }
          if (_this.queryForm.condition.onSiteExamineStart) {
            // 材料报送截止时间必须小于现场考核开始时间
            if (value.getTime() > new Date(_this.queryForm.condition.onSiteExamineStart.split(' ')[0]).getTime()) {
              return true;
            }
          }
          return false;
        }
      };
    },
    xckhsjqPickerOptions() {
      let _this = this;
      return {
        disabledDate: (value) => {
          if (_this.queryForm.condition.submitMaterialsEnd) {
            // 现场考核开始时间必须大于材料报送截止时间
            if (value.getTime() + (24 * 60 * 60 * 1000) < new Date(_this.queryForm.condition.submitMaterialsEnd.split(' ')[0]).getTime()) {
              return true;
            }
          }
          if (_this.queryForm.condition.onSiteExamineEnd) {
            // 现场考核开始时间必须小于现场考核截止时间
            if (value.getTime() > new Date(_this.queryForm.condition.onSiteExamineEnd.split(' ')[0]).getTime()) {
              return true;
            }
          }
          return false;
        }
      };
    },
    xckhsjzPickerOptions() {
      let _this = this;
      return {
        disabledDate: (value) => {
          if (_this.queryForm.condition.onSiteExamineStart) {
            // 现场考核截止时间必须大于现场考核开始时间
            if (value.getTime() + (24 * 60 * 60 * 1000) < new Date(_this.queryForm.condition.onSiteExamineStart.split(' ')[0]).getTime()) {
              return true;
            }
          }
          if (_this.queryForm.condition.scoreStart) {
            // 现场考核截止时间必须小于评分开始时间
            if (value.getTime() > new Date(_this.queryForm.condition.scoreStart.split(' ')[0]).getTime()) {
              return true;
            }
          }
          return false;
        }
      };
    },
    pfsjqPickerOptions() {
      let _this = this;
      return {
        disabledDate: (value) => {
          if (_this.queryForm.condition.onSiteExamineEnd) {
            // 评分开始时间必须大于现场考核截止时间
            if (value.getTime() + (24 * 60 * 60 * 1000) < new Date(_this.queryForm.condition.onSiteExamineEnd.split(' ')[0]).getTime()) {
              return true;
            }
          }
          if (_this.queryForm.condition.scoreEnd) {
            // 评分开始时间必须小于评分截止时间
            if (value.getTime() > new Date(_this.queryForm.condition.scoreEnd.split(' ')[0]).getTime()) {
              return true;
            }
          }
          return false;
        }
      };
    },
    pfsjzPickerOptions() {
      let _this = this;
      return {
        disabledDate: (value) => {
          if (_this.queryForm.condition.scoreStart) {
            // 评分截止时间必须大于评分开始时间
            if (value.getTime() + (24 * 60 * 60 * 1000) < new Date(_this.queryForm.condition.scoreStart.split(' ')[0]).getTime()) {
              return true;
            }
          }
          return false;
        }
      };
    }
  },
  created() {
    // 获取当前用户auths权限
    if (localStorage.getItem("sessiondata")) {
      if (JSON.parse(localStorage.getItem("sessiondata")).auths) {
        this.auths = JSON.parse(localStorage.getItem("sessiondata")).auths;
      }
    }
    graduateStudentApi.queryBaseAssessList(this.queryForm).then(res => {
      this.dataList = res.data.list;
      this.queryForm.total_ = res.data.total_;
    });
  },
  methods: {
    // 校验特殊字符$
    checkSpecial(rule, value, callback) {
      let regEn = /[`$]/im;
      if (regEn.test(value)) {
        callback(new Error(this.$t('graduateBase.specialText')))
      } else {
        callback();
      }
    },
    // 改变基地级别
    changeBaseLevel(val) {
      this.queryForm.condition.templateId = '';
      if (val) {
        graduateStudentApi.getHasDetailTemp({
          "itemCategory": "1",
          "baseTemplate": {
            "baseLevel": val
          }
        }).then(res => {
          this.options.templateId = res.data;
        });
      } else {
        this.options.templateId = [];
      }
    },
    reset() {
      this.baseLevel = [];
      Object.keys(this.queryForm.condition).forEach(key => this.queryForm.condition[key] = '');
      this.options.templateId = [];
      this.onSubmit();
    },
    onSubmit() {
      this.queryForm.pageNum_ = 1;
      this.getListData();
    },
    getListData() {
      graduateStudentApi.queryBaseAssessList(this.queryForm).then((res) => {
        this.dataList = res.data.list;
        this.queryForm.total_ = res.data.total_;
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 轮询直到获取key值的接口返回
    cycleToGetKey() {
      setTimeout(() => {
        let currentIds = [];
        if (this.multipleSelection.length > 0) {
          this.multipleSelection.forEach((element) => {
            currentIds.push(element.id);
          });
        }
        graduateStudentApi.exportBaseAssessSet({
          "submitMaterialsStart": this.queryForm.condition.submitMaterialsStart,
          "submitMaterialsEnd": this.queryForm.condition.submitMaterialsEnd,
          "onSiteExamineStart": this.queryForm.condition.onSiteExamineStart,
          "onSiteExamineEnd": this.queryForm.condition.onSiteExamineEnd,
          "scoreStart": this.queryForm.condition.scoreStart,
          "scoreEnd": this.queryForm.condition.scoreEnd,
          "baseLevel": this.queryForm.condition.baseLevel,
          "publishStatus": this.queryForm.condition.publishStatus,
          "templateId": this.queryForm.condition.templateId,
          "batch": this.queryForm.condition.batch,
          "selectRowIds": currentIds
        }).then(res => {
          if (res.success) {
            this.$refs.downloadRef.close();
            this.exportButton = false;
            this.normalDelayRequest(res.key, res.msg);
          } else {
            this.cycleToGetKey();
          }
        });
      }, 3000);
    },
    // 导出异步
    delayRequest(key, name) {
      setTimeout(() => {
        graduateStudentApi.downloadGetKey(key, name).then(res => {
          this.exportResult = res.data;
          if (res.code == 200 && res.data.status) {
            this.exportButton = false;
            let path =
              '/api/practiceservice/export/file?path=' +
              res.data.path + '&name=' + name;
            // window.open(path);
            window.location.href = path;
            this.$message.success(this.$t('result.exportSuccessfully'));
            this.$refs.downloadRef.close();
          } else {
            this.delayRequest(key, name);
          }
        });
      }, 3000);
    },
    // Normal导出异步
    normalDelayRequest(key, name) {
      setTimeout(() => {
        graduateStudentApi.downloadGetKey(key).then(res => {
          this.exportResult = res.data;
          if (res.code == 200 && res.data.status) {
            this.exportButton = false;
            let path =
              '/api/practiceservice/export/file?path=' +
              res.data.path + '&name=' + name;
            // window.open(path);
            window.location.href = path;
            this.$message.success(this.$t('result.exportSuccessfully'));
            this.$refs.downloadRef.close();
          } else {
            this.delayRequest(key, name);
          }
        });
      }, 3000);
    },
    // 导出基地考核设置
    exportBaseAssessSet() {
      // 1、第一步：调该接口，获取key值以及msg中的文件名
      // 2、第二步：将key值放入接口传参
      // 3、第三步：传入path值以及name(msg中的文件名)值，下载文件
      this.exportResult = null;
      this.$refs.downloadRef.open();
      this.exportButton = true;
      this.cycleToGetKey();
    },
    // 新增基地考核设置
    addBaseAssessSet() {
      this.dialogMode = 'add';
      this.dialogVisible = true;
    },
    // 关闭x事件
    beforeClose: function (done) {
      this.cancel();
    },
    // 取消
    cancel() {
      let allIsEmpty = true;
      for (let key in this.dialogForm) {
        if (this.dialogForm[key]) {
          allIsEmpty = false;
        }
      }
      if (allIsEmpty) {
        this.innerVisible = false;
        this.dialogVisible = false;
      } else {
        this.innerVisible = true;
      }
    },
    handleDialogSelectionChange(val) {
      this.dialogMultipleSelection = val;
    },
    // 发布基地考核设置--表格
    publishBaseAssessSet(row) {
      if (row.publishStatus === 1) {
        this.$eduConfirm(this.$t('baseAssessSetting.disabledPublish')).then(_ => {});
      } else {
        graduateStudentApi.publishBaseAssessSet({
          "id": row.id
        }).then(res => {
          if (res.code === 200) {
            this.$message.success(this.$t('graduateBase.pushlishSuccessuly'));
            this.onSubmit();
          }
        });
      }
    },
    // 编辑基地考核设置--表格
    editBaseAssessSet(row) {
      this.dialogMode = 'edit';
      this.dialogVisible = true;
      graduateStudentApi.queryAssessDetails(row.id).then(res => {
        if (res.code === 200) {
          this.mainBaseAssessInfo = res.data;
        }
      });
    },
    // 删除基地考核设置操作
    deleteBaseAssessSettingRow(id) {
      graduateStudentApi.removeBaseAssessSet({
        "id": id
      }).then(res => {
        if (res.code === 200) {
          this.$message.success(this.$t('common.tips.deleteSuccess'));
          this.onSubmit();
        }
      });
    },
    // 删除基地考核设置--表格
    deleteBaseAssessSet(row) {
      if (row.publishStatus === 1) {
        this.$delConfirm(this.$t('baseAssessSetting.removeBaseInfoTip')).then(_ => {
          this.deleteBaseAssessSettingRow(row.id);
        });
      } else {
        this.$delConfirm().then(_ => {
          this.deleteBaseAssessSettingRow(row.id);
        });
      }
    },
    // 查看基地考核设置详情--表格
    selectBaseAssessSetDetail(row) {
      this.dialogMode = 'details';
      this.dialogVisible = true;
      graduateStudentApi.queryAssessDetails(row.id).then(res => {
        if (res.code === 200) {
          this.mainBaseAssessInfo = res.data;
        }
      });
    },
    handleSizeChange(val) {
      this.queryForm.pageSize_ = val;
      this.getListData();
    },
    handleCurrentChange(val) {
      this.queryForm.pageNum_ = val;
      this.getListData();
    }
  },
  watch: {
    auths: {
      handler(newVal) {
        if (newVal && Array.isArray(newVal) && newVal.length > 0) {
          newVal.some(item => {
            if (item.authCode === 'graduateStu-baseAssessSet-export') {
              this.permitToExport = true;
            }
            if (item.authCode === 'graduateStu-baseAssessSet-add') {
              this.permitToAdd = true;
            }
            if (item.authCode === 'graduateStu-baseAssessSet-edit') {
              this.permitToEdit = true;
            }
            if (item.authCode === 'graduateStu-baseAssessSet-delete') {
              this.permitToDelete = true;
            }
            if (item.authCode === 'graduateStu-baseAssessSet-details') {
              this.permitToDetail = true;
            }
            if (item.authCode === 'graduateStu-baseAssessSet-publish') {
              this.permitToPublish = true;
            }
          });
        }
      },
      deep: true,
      immediate: true
    }
    
  }
}
</script>
<style lang="scss" scoped>
  .condition-title {
    color: #2b3b4e;
    font-size: 18px;
    line-height: 24px;
    font-weight: bold;
  }
  .publish-btn-container ::v-deep {
    .el-button {
      cursor: auto;
    }
    .el-button--danger {
      padding: 9px 15px;
      min-width: 0;
    }
  }
  .base-assess-set-dialog ::v-deep {
    .el-dialog .el-dialog__header {
      display: none!important;
    }
    .el-dialog__body {
      padding: 15px 0 15px 0!important;
    }
  }
</style>
